package com.isc.udpCommunication01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 1.编写一个接收端A(服务器端)和一个发送端B(客户端)
 * 2.接收端A在9999端口等待接收数据
 * 3.发送端B向接收端A发送数据"hello,明天吃火锅~"
 * 4.接收端A接收到发送端B发送的数据，回复"好的明天见",然后退出
 * 5.发送端接收回复的数据，再退出
 */
public class Server {
    public static void main(String[] args) throws IOException {
        //接收端
        int port = 9999;
        DatagramSocket datagramSocket = new DatagramSocket(9999);
        System.out.println("正在监听9999，等待接收数据...");

        //获取发送端的消息
        byte[] buf = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);
        datagramSocket.receive(datagramPacket);
        //得到数据报中的数据
        byte[] data = datagramPacket.getData();
        int dataLength = datagramPacket.getLength();
        System.out.println("接收到的消息是:" + new String(data, 0, dataLength));

        //回复之前发送端消息
        byte[] relpy = "好的明天见".getBytes();
        dataLength = relpy.length;
        DatagramPacket replyPacket = new DatagramPacket(relpy, dataLength, InetAddress.getByName("127.0.0.1"), 9998);
        datagramSocket.send(replyPacket);
        System.out.println("回复消息成功~");

        //关闭资源
        datagramSocket.close();
    }
}
